package com.automapper.execute.impl;

import java.util.List;

import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.automapper.execute.Execute;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.PropertiesFacade;
import com.automapper.utils.SqlSourceBuilderUtils;

public class BaseExecute implements Execute {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseExecute.class);
	
	private SqlBuilderTemplate sqlBuilder;
	
	@Override
	public void process(MetaObject metaStatementHandler, Invocation invocation, PropertiesFacade propertiesFacade) throws Exception {
		//获取入库数据
		Object parameterObject = metaStatementHandler.getValue("delegate.boundSql.parameterObject");
		Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
		
		String newSql = sqlBuilder.buildSql(parameterObject, propertiesFacade);
		logger.debug("Auto generated sql:" + newSql);
		
		SqlSource sqlSource = SqlSourceBuilderUtils.buildSqlSource(configuration, newSql, parameterObject.getClass());
		List<ParameterMapping> parameterMappings = sqlSource.getBoundSql(parameterObject).getParameterMappings();
		metaStatementHandler.setValue("delegate.boundSql.sql", sqlSource.getBoundSql(parameterObject).getSql());
		metaStatementHandler.setValue("delegate.boundSql.parameterMappings", parameterMappings);
	}
}
